package com.mazong.servershirodemo.shiro;

import com.mazong.servershirodemo.pojo.TbPermission;
import com.mazong.servershirodemo.pojo.TbRole;
import com.mazong.servershirodemo.pojo.TbUser;
import com.mazong.servershirodemo.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    /**
     * TODO 检查授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录用户名
        String name = (String) principals.getPrimaryPrincipal();
        //根据用户名去数据库查询用户信息
        TbUser user = loginService.getUserByName(name);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (TbRole role : user.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (TbPermission permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * TODO 执行验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (token.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        UsernamePasswordToken t = (UsernamePasswordToken)token;
        String name = t.getUsername();
        String pass = String.valueOf(t.getPassword());

//        String name = token.getPrincipal().toString();
//        String pass = String.valueOf(token.getCredentials().toString());


        log.info("doGetAuthenticationInfo,name={},pass={},getname={}", name, pass,getName());

        TbUser user = loginService.getUserByName(name);
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            if(!user.getUserPass().equals(pass)) {
                log.info("密码错误，name={},pass(error)={}", name, user.getUserPass());
            }
            else {
                log.info("密码正确，name={},pass(ok)={}", name, pass);
            }

            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getUserPass().toString(), getName());
            return simpleAuthenticationInfo;
        }
    }
}
